﻿using Syspetro.Core.Resources;
using BJ.AuthEntity.Models;
using Syspetro.Core.AppDeal;
using Syspetro.Core.CommandBus;
using Syspetro.Core.GoogleAuth.Google2;
using Syspetro.Deploy.Managers;
using System;
using Syspetro.Core.SysInterface;

namespace BJ.AuthDomain.Commands
{
    /// <summary>
    /// Google验证
    /// </summary>
    public class GoogleVerifyCommand : Command
    {
        public string Captcha { get; set; }
        public Guid UserId { get; set; }
        public bool IsAdmin { get; set; }
    }
    public interface IGoogleVerifyCommandHandler : ICommandHandler<GoogleVerifyCommand>, ITransientService
    {

    }
    public class GoogleVerifyCommandHandler : CommandHandler<GoogleVerifyCommand>, IGoogleVerifyCommandHandler
    {
        readonly IFreeSql _freeSql;
        readonly IAuthorizationManager _authorization;
        public GoogleVerifyCommandHandler(IAuthorizationManager authorization, IFreeSql freeSql)
        {
            _freeSql = freeSql;
            _authorization = authorization;
        }
        public override SpActionResult<string> Execute(GoogleVerifyCommand command)
        {
            if (command.UserId == Guid.Empty)
            {
                command.UserId = _authorization.GetUserId;
                command.IsAdmin = _authorization.IsAdmin;
            }
            if (command.IsAdmin)
            {
                var user = _freeSql.Select<AdminUser>().Where(t => t.Id == command.UserId).First();
                GoogleAuthenticatorProvider2 google = new();
                if (!google.Validate(user.Enable2FA, command.Captcha))
                    return new SpActionResult<string> { Success = false, Msg = SharedResource.CodeError };
                return new SpActionResult<string> { Success = true, Msg = SharedResource.VerifyCodeOk };
            }
            else
            {
                var user = _freeSql.Select<User>().Where(t => t.Id == command.UserId).First();
                GoogleAuthenticatorProvider2 google = new();
                if (!google.Validate(user.Enable2FA, command.Captcha))
                    return new SpActionResult<string> { Success = false, Msg = SharedResource.CodeError};
                return new SpActionResult<string> { Success = true, Msg = SharedResource.VerifyCodeOk };
            }
        }
    }
}
